<?php

class Nuo_View_Helper_Toolbar extends Zend_View_Helper_Abstract
{

	/**
	 * @property array
	 *
	 */
	protected $_config = array();

	/**
	 * @property int
	 */
	protected $_maxLevel = 3;

	/**
	 * @param array $config
	 * @param string $menu
	 * @param string $submenu
	 * @param int max_level
	 * @return xhtml
	 */
	public function toolbar($config, $toolbar, $max_level= 1)
	{
		$items = Nuo::getApi('Toolbar')->getItems($toolbar);
		
		// process menu to know what is happend with menu items.
		$level = 0;
		$this -> _maxLevel = $max_level;
		$this -> _config = $config;

		$xhtml = '';
		foreach ($items as $item)
		{
			$xhtml .= $this -> renderItem($item, $level);
		}

		return sprintf('<ul class="%s">%s</ul>', $this -> getConfig('menuClass', 'uiMenu'), $xhtml);
	}

	/**
	 * get config by name
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	public function getConfig($name, $default = '')
	{
		return isset($this -> _config[$name]) ? $this -> _config[$name] : $default;
	}

	/**
	 * @param  array $items
	 * @return string
	 */
	public function renderSubmenu($items, $level)
	{
		// check if empty item
		if (empty($items))
		{
			return '';
		}

		$xhtml = '';
		foreach ($items as $item)
		{
			$xhtml .= $this -> renderItem($item, $level + 1);
		}
		return sprintf('<ul>%s</ul>', $xhtml, $level);
	}

	/**
	 * render a menu item
	 * @param array $item {children: array(), plugin: mixed, label, menu,
	 * submenu, level}
	 */
	public function renderItem($item, $level = 0)
	{
		$hasChild = isset($item['children']) && !empty($item['children']) && $level < $this -> _maxLevel;
		$data = $item['data'];
		$type = $data['type'];

		if ($type == 'plugin')
		{
			$data = call_user_func($data['plugin'], $data);
		}
		
		if(empty($data)){
			return ;
		}
		
		$ul = '';
		$url = '';

		if (isset($data['uri']) && !empty($data['uri']))
		{
			$url = $data['uri'];
		}
		else
		{
			$url = $this -> view -> url($data['options'], $data['route'], $data['reset'], $data['encode']);
		}

		$li = sprintf('<a href="%s">%s</a>', $url, $data['label']);

		if ($hasChild)
		{
			$ul = $this -> renderSubmenu($item['children'], $level);
		}

		return sprintf('<li class="%s">%s%s</li>', $item['name'], $li, $ul);
	}

}
